
var net = require('net');
var http = require('http');
var url = require('url');
var paperboy = require('./paperboy.js');

function randomPort() {
    var server = net.createServer();
    server.listen(0);
    var port = server.address().port;
    server.close();
    return port;
}

function dumpvar(obj) {
    var out = '';
    for (var i in obj) {
        if(out!='') out += ',';
        if(typeof(i)=='number') {
            out += i;
        } else {
            out += '"' + i + '"';
        }
        out += ' : "' + obj[i] + '"';
    }
    return out;
}

var args = {};

function parseArgs() {
    var start;

    for(start=1; start<process.argv.length; start++) {
        var v = process.argv[start];
        if(v.substring(v.length-3)=='.js') {
            start += 1;
            break;
        }
    }

    for(; start<process.argv.length; start++) {
        var v = process.argv[start];
        var loc = v.indexOf('=');
        if(loc>=0) {
            args[v.substring(0, loc)] = v.substring(loc+1);
        } else {
            args[v] = '';
        }
    }
}

function getArgs() {
    return args;
}

function processArgs(methods) {
    for(var i in args) {
        if(methods.hasOwnProperty(i)) {
            methods[i](args[i]);
        }
    }
}

function getUrlData(urla, response, error) {
    var host = url.parse(urla);
    var path = host['pathname'];
    if(host['search']!=null) path += host['search'];
    var port = 80;
    host = host['host'];
    var loc = host.indexOf(':')
    if(loc>=0) {
        port = host.substring(loc+1);
        host = host.substring(0, loc); 
    }

	var options = {
		'host' : host,
		'port' : port,
		'path' : path,
		'method' : 'GET',
		'headers' : { 'Content-Type': 'application/x-www-form-urlencoded' },
	};
	
    if(response==null) {
        response = function(res) { };
    }
    if(error==null) {
        error = function(err) { };
    }

	var req = http.request(options, response);
    req.on('error', error);
	req.end();
    return req;
}

function processHttpRequest(req, res, methods, front_end) {
    var path = String(req.url);

    if(path.substring(0, 5)=='/api.') {
        var method = path.substring(5);
        var arg = '';
        var loc = method.indexOf('?');
        if(loc>=0) {
            arg = method.substring(loc+1);
            method = method.substring(0, loc);
        }
        if(methods.hasOwnProperty(method)) {
            methods[method](decodeURIComponent(arg), req, res);
            return;
        } else {
            // invalid 
            return;
        }
    }

    if(!front_end) {
        res.writeHead(404);
        res.end();
        return;
    }

    if(path=='/') path = '/index.html';
    paperboy.deliver('front-end', req, res);
}

var master_addr = '127.0.0.1:8123';

function setMasterAddr(v) {
    master_addr = v;
}

function getMasterAddr(v) {
    return master_addr;
}

function rlog(msg) {
//    getUrlData('http://' + master_addr + '/api.rlog?' + encodeURIComponent(msg), null, null);
}

function log(msg) {
    console.log(msg);
}

module.exports.randomPort = randomPort;
module.exports.dumpvar = dumpvar;
module.exports.parseArgs = parseArgs;
module.exports.getArgs = getArgs;
module.exports.processArgs = processArgs;
module.exports.getUrlData = getUrlData;
module.exports.processHttpRequest = processHttpRequest;
module.exports.setMasterAddr = setMasterAddr;
module.exports.getMasterAddr = getMasterAddr;
module.exports.rlog = rlog;
module.exports.log = log;
